import {OrderByOption} from "../types";

/**
 * SQL查询构建工具类
 * 提供用于构建SQL查询语句的方法
 */
export class QueryBuilderUtils {
  /**
   * 构建查询的ORDER BY子句
   * @param orderBy 排序条件，可以是字符串或对象
   * @returns 构建好的ORDER BY子句，不包含"ORDER BY"前缀
   */
  public static buildOrderByClause<T>(orderBy: string | OrderByOption<T> | undefined): string | undefined {
    if (!orderBy) {
      return undefined;
    }

    if (typeof orderBy === 'string') {
      return orderBy;
    }

    const orderByParts = Object.entries(orderBy).map(([key, direction]) => `${key} ${direction}`);
    if (orderByParts.length === 0) {
      return undefined;
    }

    return orderByParts.join(', ');
  }

  /**
   * 构建查询的WHERE子句
   * @param conditions WHERE条件对象
   * @returns { clause: string, params: any[] } WHERE子句和参数值数组，不包含"WHERE"前缀
   */
  public static buildWhereClause<T>(conditions: Record<string, any>): { clause: string, params: any[] } {
    const params: any[] = [];

    if (!conditions || Object.keys(conditions).length === 0) {
      return {clause: '', params};
    }

    const whereConditions = Object.entries(conditions).map(([key, value]) => {
      params.push(value);
      return `${key} = ?`;
    });

    return {
      clause: whereConditions.join(' AND '),
      params
    };
  }

  /**
   * 构建分页限制子句
   * @param limit 限制数量
   * @param offset 偏移量
   * @returns { clause: string, params: number[] } LIMIT/OFFSET子句和参数
   */
  public static buildPaginationClause(limit?: number, offset?: number): { clause: string, params: number[] } {
    const params: number[] = [];
    let clause = '';

    if (limit !== undefined) {
      clause = 'LIMIT ?';
      params.push(limit);

      if (offset !== undefined) {
        clause += ' OFFSET ?';
        params.push(offset);
      }
    }

    return {clause, params};
  }
}
